package com.evan.review.architecture.mvi.viewmodel;

import com.evan.review.architecture.mvi.intent.CounterIntent;
import com.evan.review.architecture.mvi.viewstate.CounterViewState;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.subjects.BehaviorSubject;


/**
 * MVI架构中的ViewModel
 * 负责处理Intent并更新ViewState
 */
public class CounterViewModel {
    
    // 使用BehaviorSubject存储和发射状态
    private final BehaviorSubject<CounterViewState> stateSubject = BehaviorSubject.createDefault(CounterViewState.initial());
    
    /**
     * 处理Intent并更新状态
     */
    public void processIntents(CounterIntent intent) {
        // 获取当前状态
        CounterViewState currentState = stateSubject.getValue();
        
        // 模拟异步操作
        stateSubject.onNext(currentState.loading());
        
        // 根据Intent类型处理不同的业务逻辑
        if (intent instanceof CounterIntent.IncrementIntent) {
            handleIncrement();
        } else if (intent instanceof CounterIntent.DecrementIntent) {
            handleDecrement();
        } else if (intent instanceof CounterIntent.ResetIntent) {
            handleReset();
        }
    }
    
    /**
     * 返回状态Observable，供View订阅
     */
    public Observable<CounterViewState> states() {
        return stateSubject;
    }
    
    /**
     * 处理增加计数的逻辑
     */
    private void handleIncrement() {
        // 模拟网络延迟
        simulateNetworkDelay();
        
        // 获取当前状态
        CounterViewState currentState = stateSubject.getValue();
        
        // 更新状态
        int newCount = currentState.getCount() + 1;
        stateSubject.onNext(currentState.success(newCount));
    }
    
    /**
     * 处理减少计数的逻辑
     */
    private void handleDecrement() {
        // 模拟网络延迟
        simulateNetworkDelay();
        
        // 获取当前状态
        CounterViewState currentState = stateSubject.getValue();
        
        // 更新状态
        int newCount = currentState.getCount() - 1;
        stateSubject.onNext(currentState.success(newCount));
    }
    
    /**
     * 处理重置计数的逻辑
     */
    private void handleReset() {
        // 模拟网络延迟
        simulateNetworkDelay();
        
        // 获取当前状态
        CounterViewState currentState = stateSubject.getValue();
        
        // 更新状态
        stateSubject.onNext(currentState.success(0));
    }
    
    /**
     * 模拟网络延迟
     */
    private void simulateNetworkDelay() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
            
            // 处理错误
            CounterViewState currentState = stateSubject.getValue();
            stateSubject.onNext(currentState.error("操作被中断"));
        }
    }
} 